package org.inspursc.s0517.health.evaluation.service.impl;

import com.google.common.collect.Maps;
import org.inspursc.s0517.health.evaluation.converter.QuestionCategoryConverter;
import org.inspursc.s0517.health.evaluation.dao.QuestionCategoryDao;
import org.inspursc.s0517.health.evaluation.dto.CategoryDTO;
import org.inspursc.s0517.health.evaluation.dto.QuestionCategoryDTO;
import org.inspursc.s0517.health.evaluation.dto.QuestionDTO;
import org.inspursc.s0517.health.evaluation.entity.QuestionCategory;
import org.inspursc.s0517.health.evaluation.service.QuestionCategoryService;
import org.inspursc.s0517.health.evaluation.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 分类管理类实现
 *
 * @author B_Dream
 * @date 2018/5/22 14:39
 */
@Service
public class QuestionCategoryServiceImpl implements QuestionCategoryService {

    @Autowired
    QuestionCategoryDao categoryDao;

    @Autowired
    QuestionService questionService;


    @Override
    public List<QuestionCategoryDTO> getCategory(Integer parentId) {
        List<QuestionCategory> categories = categoryDao.findByParentId(parentId);
        List<QuestionCategoryDTO> dtos = categories.stream().map(QuestionCategoryConverter::converter).collect(Collectors.toList());
        return dtos;
    }



    @Override
    public List<QuestionCategoryDTO> getCategoryOfSurvey( List<QuestionDTO> quDTOS) {
        Set<Integer> cateIds = quDTOS.stream().map(QuestionDTO::getCategoryId).collect(Collectors.toSet());
        List<QuestionCategory> categories = categoryDao.findAllById(cateIds);
        List<QuestionCategory> cates = categoryDao.findAllById(categories.stream().map(QuestionCategory::getParentId).collect(Collectors.toSet()));
//        List<QuestionCategory> cates = new ArrayList<>();
//        for (QuestionCategory cate : categories) {
//            if (cate.getParentId() != 0) {
//                cates.add(categoryDao.getOne(cate.getParentId()));
//            }
//        }
        categories.addAll(cates);
        Set<QuestionCategoryDTO> dtoSet = categories.stream().map(QuestionCategoryConverter::converter).collect(Collectors.toSet());
        List<QuestionCategoryDTO> dtos=new ArrayList<>(dtoSet);
        // 排序
        Collections.sort(dtos, new Comparator<QuestionCategoryDTO>(){
            public int compare(QuestionCategoryDTO c1, QuestionCategoryDTO c2) {
                //按id进行升序排列
                if(c1.getId() > c2.getId()){
                    return 1;
                }
                if(c1.getId() == c2.getId()){
                    return 0;
                }
                return -1;
            }
        });
        List<QuestionCategoryDTO> dtoTree = this.toTreeList(dtos);
        Map<Integer, List<QuestionDTO>> quSorts = sort(quDTOS);
        for (QuestionCategoryDTO dto : dtoTree) {
            addQuestion(dto, quSorts);
        }
        return dtoTree;
    }

    @Override
    public CategoryDTO saveCategory(CategoryDTO categorydto) {
        QuestionCategory category = QuestionCategoryConverter.converterNoQu(categorydto);
        QuestionCategory newCategory = categoryDao.save(category);
        CategoryDTO dto = QuestionCategoryConverter.converterNoQu(newCategory);
        return dto;
    }

    @Override
    public Boolean deleteCategory(Integer id) {
        try {
            List<QuestionCategory> categorys = categoryDao.findByParentId(id);
            if (categorys != null && categorys.isEmpty()) {
                categoryDao.deleteById(id);
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }


    @Override
    public List<QuestionCategoryDTO> findAll() {

        List<QuestionCategory> categories = categoryDao.findAll();

        List<QuestionCategoryDTO> categoryDTOS = categories.stream().map(QuestionCategoryConverter::converter).collect(Collectors.toList());

        return toTreeList(categoryDTOS);

    }
    @Override
    public List<QuestionCategoryDTO> findByTypeId(int typeId) {

        List<QuestionCategory> questionCategories = categoryDao.findByTypeId(typeId);

        List<QuestionCategoryDTO> quetionCategoriesDTO = questionCategories.stream().map(QuestionCategoryConverter::converter).collect(Collectors.toList());

        return toTreeList(quetionCategoriesDTO);
    }


    @Override
    public List<QuestionCategoryDTO> findBatch(Set<Integer> ids) {
        List<QuestionCategory> categories= categoryDao.findAllById(ids);
        List<QuestionCategoryDTO> categoryDTOS=categories.stream().map(QuestionCategoryConverter::converter).collect(Collectors.toList());
        return categoryDTOS;
    }
    @Override
    public List<QuestionCategoryDTO> findAllAndQustion() {
        List<QuestionCategoryDTO> lists = findAll();
        List<QuestionDTO> dtos = questionService.listQuestionNoRadio();
        Map<Integer, List<QuestionDTO>> quSorts = sort(dtos);
        for (QuestionCategoryDTO dto : lists) {
            addQuestion(dto, quSorts);
        }
        return lists;
    }
    @Override
    public List<QuestionCategoryDTO> findQuestionByTypeId(int typeId){
        List<QuestionCategoryDTO> lists = findByTypeId(typeId);
        List<QuestionDTO> dtos = questionService.listQuestionNoRadio();
        Map<Integer, List<QuestionDTO>> quSorts = sort(dtos);
        for (QuestionCategoryDTO dto : lists){
            addQuestion(dto, quSorts);
        }
        return lists;

    }



    /**
     * 增加问题列表
     *
     * @param dto
     * @param quSorts
     */
    private void addQuestion(QuestionCategoryDTO dto, Map<Integer, List<QuestionDTO>> quSorts) {
        if (!StringUtils.isEmpty(dto.getChildren())) {
            for (QuestionCategoryDTO dto1 : dto.getChildren()) {
                if (quSorts.containsKey(dto1.getId())) {
                    dto1.setQuestions(quSorts.get(dto1.getId()));
                }
                addQuestion(dto1, quSorts);
            }
        }
    }


    /**
     * 对问题的分类id进行分类
     *
     * @param list
     * @return
     */
    private Map<Integer, List<QuestionDTO>> sort(List<QuestionDTO> list) {
        Map<Integer, List<QuestionDTO>> quMaps = Maps.newHashMap();
        for (QuestionDTO qu : list) {
            if (quMaps.containsKey(qu.getCategoryId())) {
                List<QuestionDTO> oldList = quMaps.get(qu.getCategoryId());
                oldList.add(qu);
            } else {
                List<QuestionDTO> dtos = new ArrayList<>();
                dtos.add(qu);
                quMaps.put(qu.getCategoryId(), dtos);
            }

        }
        return quMaps;
    }

    /**
     * 组装树
     *
     * @param moduleList
     * @return
     */
    private List<QuestionCategoryDTO> toTreeList(List<QuestionCategoryDTO> moduleList) {
        Map<Object, QuestionCategoryDTO> maps = new HashMap<>(16);
        List<QuestionCategoryDTO> list = new ArrayList<>();
        for (QuestionCategoryDTO module : moduleList) {
            addTreeNode(module, maps, list);
        }
        return list;
    }


    /**
     * 增加树的节点
     *
     * @param module
     * @param maps
     * @param list
     */
    private void addTreeNode(QuestionCategoryDTO module, Map<Object, QuestionCategoryDTO> maps,
                             List<QuestionCategoryDTO> list) {
        if (maps.containsKey(module.getId())) {
            maps.get(module.getId()).setEntity(module);
        } else {
            maps.put(module.getId(), module);
        }
        if (0 == module.getParentId()) {
            list.add(maps.get(module.getId()));
        } else {
            if (maps.containsKey(module.getParentId())) {
                maps.get(module.getParentId()).addChildren(module);
            } else {
                QuestionCategoryDTO parent = new QuestionCategoryDTO();
                parent.addChildren(module);
                maps.put(module.getParentId(), parent);
            }
        }
    }

 }

